package cn.wmw.xyy.mq.consumer;

import cn.wmw.xyy.bo.CourseOrderPayBo;
import cn.wmw.xyy.bo.KillCoursePreOrderBo;
import cn.wmw.xyy.domain.PayOrder;
import cn.wmw.xyy.exception.GlobalException;
import cn.wmw.xyy.exception.GlobalExceptionEnum;
import cn.wmw.xyy.service.IPayOrderService;
import com.alibaba.fastjson.JSON;
import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.payment.common.models.AlipayTradeQueryResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.nio.charset.StandardCharsets;

@Slf4j
@Component
@RocketMQMessageListener(
        consumerGroup = "consumer-pay-timeout-group",
        topic = "pay-timeout-topic",
        selectorExpression = "pay-timeout-tag"
)
public class PayTimeoutConsumer implements RocketMQListener<MessageExt> {
    @Autowired
    private IPayOrderService payOrderService;

    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

    @Autowired
    private RedissonClient redissonClient;
    @Override
    public void onMessage(MessageExt messageExt) {
        try {
            // 1.参数校验
            byte[] body = messageExt.getBody();
            if (body.length == 0) {
                // 1.应该记录进入异常的次数，如果超过三次，那么应该通知管理员，手动处理
                log.error("支付消费发生异常，异常信息为：消息信息为空！");
                throw new GlobalException(GlobalExceptionEnum.ERROR);
            }

            CourseOrderPayBo courseOrderPayBo = JSON.parseObject(new String(body, StandardCharsets.UTF_8), CourseOrderPayBo.class);
            // 2.业务校验
            String orderNo = courseOrderPayBo.getOrderNo();
            PayOrder payOrder = payOrderService.selectByOrderNo(orderNo);

            if (payOrder == null){
                log.info("支付延迟消息处理异常，异常信息为：支付单信息不存在，订单号为：" + orderNo);
                return;
            }
//            if (!PayOrder.WAIT_PAY.equals(payOrder.getPayStatus())){
//                return;
//            }
            // 3.查询支付宝看订单状态是否为支付
            AlipayTradeQueryResponse response = Factory.Payment.Common().query(orderNo);
            String tradeStatus = response.getTradeStatus();

            // 如果是秒杀订单，那么还需要处理秒杀订单后续业务
            Object o = redisTemplate.opsForValue().get("preOrder:" + orderNo);
            boolean isKill = !StringUtils.isEmpty(o);
            if ("TRADE_SUCCESS".equals(tradeStatus) || "TRADE_FINISHED".equals(tradeStatus)){ // 已支付
            }else { // 没有支付
                // 1.修改支付单状态
                Factory.Payment.Common().cancel(orderNo);
                if (isKill){
                    // 1.还库存
                    KillCoursePreOrderBo killCoursePreOrderBo = JSON.parseObject(JSON.toJSONString(o), KillCoursePreOrderBo.class);
                    Long activityId = killCoursePreOrderBo.getActivityId();
                    Long killCourseId = killCoursePreOrderBo.getKillCourseId();
                    Long loginId = killCoursePreOrderBo.getUserId();
                    RSemaphore semaphore = redissonClient.getSemaphore(activityId + ":" + killCourseId);
                    semaphore.addPermits(1);
                    // 2.删除购买记录
                    redisTemplate.delete(loginId + ":" + activityId + ":" + killCourseId);
                    // 1.删预创订单信息
                    redisTemplate.delete("preOrder:" + orderNo);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("支付超时处理失败，失败原因为：{}", e.getMessage());
            throw new GlobalException(GlobalExceptionEnum.ERROR);
        }

    }
}
